package the.broccoli.uc.controller;

import io.swagger.annotations.ApiParam;
import net.sf.ehcache.constructs.nonstop.concurrency.CacheOperationUnderExplicitLockCallable;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.wisteria.framework.web.APIResult;
import the.broccoli.auth.UserContext;
import the.broccoli.uc.dto.RoleCondition;
import the.broccoli.uc.entity.Role;
import the.broccoli.uc.service.IRoleService;
import the.broccoli.uc.service.IUserRoleService;
import the.broccoli.uc.vo.RoleSelect;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户与角色控制器
 *
 * @author lei.liu
 * @since 2020-04-09 17:45:30
 */
@RestController
@RequestMapping("/uc/user/role")
public class UserRoleController {

    @Resource
    private IUserRoleService userRoleService;

    @Resource
    private IRoleService roleService;

    @PostMapping("/add")
    public APIResult add(
            @ApiParam(name = "userId", value = "用户ID", required = true)
            @RequestParam(name = "userId", required = true) String userId,
            @ApiParam(name = "roleIdList", value = "角色ID", required = true)
            @RequestParam(name = "roleIdList", required = true) List<String> roleIdList
    ) {
        userRoleService.save(userId, roleIdList, UserContext.userId(), UserContext.userName());
        return APIResult.success();
    }

    @GetMapping("/tree/{userId}")
    public APIResult roleSelect(
            @ApiParam(name = "userId", value = "用户ID", required = true)
            @PathVariable(value = "userId") String userId
    ){

        List<String> currentUserRoleIdList = userRoleService.getRoleIdList(UserContext.userId());
        if (CollectionUtils.isEmpty(currentUserRoleIdList)) {
            return APIResult.success(null);
        }
        List<String> roleIdList = new ArrayList<>(currentUserRoleIdList);
        List<String> subRoleIdList = roleService.getRoleIdList(currentUserRoleIdList);
        if (!CollectionUtils.isEmpty(subRoleIdList)) {
            roleIdList.addAll(subRoleIdList);
        }

//        RoleCondition condition = new RoleCondition();
//        condition.setTenantId(UserContext.tenantId());
//        condition.setRoleParentIdList(currentUserRoleIdList);
//        List<Role> roleList = roleService.listByCondition(condition);
//        List<String> roleIdList = new ArrayList<>();
//        for (Role entity : roleList) {
//            roleIdList.add(entity.getRoleId());
//        }

        return APIResult.success(new RoleSelect(roleService.getTree(roleIdList, currentUserRoleIdList), userRoleService.getRoleIdList(userId)));
    }
}